package com.app.newiptv.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.newiptv.R;
import com.app.newiptv.adaper.ChanelAllAdapter;
import com.app.newiptv.adaper.MainChanelAdapter;
import com.app.newiptv.adaper.ProgramAdapter;
import com.app.newiptv.bean.allchannels.MainChanel;
import com.app.newiptv.presenter.AllChannelsPresenter;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.Paths;
import com.app.newiptv.view.FocusGridLayoutManager;
import com.app.newiptv.view.MyRecycleView;


/**
 * Created by Shinelon on 2017/11/8.
 */

public class PlayWindowFragment extends Fragment implements AllChannelsPresenter.Callback {
    private PlayerActivity mContext;
    private MyRecycleView mOne_stage_rv;
    private MyRecycleView mTwo_stage_rv;
    private MyRecycleView mThree_stage_rv;
    private View mline_two;
    private View mline_one;
    private AllChannelsPresenter allChannelsPresenter;
    private int focusPosition;
    private MainChanelAdapter firstAdapter;
    private ChanelAllAdapter sencondAllAdapter;
    private ProgramAdapter thirdAdapter;
    private View view;
    private FragmentManager fragmentManager;
    private int FIRST_LIST = 0x1;
    private int HIDE_FRAGMENT = 0x2;
    private Handler mainHandler;
    int categoryIndex = 0;
    int channelIndex = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FIRST_LIST) {
                mOne_stage_rv.requestFocus();
                firstAdapter.selected();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mTwo_stage_rv.requestFocus();
                    }
                },100);
            } else if (msg.what == HIDE_FRAGMENT) {
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
            }
        }
    };

    public void setContext(PlayerActivity context) {
        this.mContext = context;
    }

    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    public void setMainHandler(Handler handler) {
        this.mainHandler = handler;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_winow, container, false);
        initWindow();
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(FIRST_LIST);
        mHandler.removeMessages(HIDE_FRAGMENT);
    }

    public void initWindow() {
        initView();
        initData();
        setLisenter();
        loadData();
        mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT, 6000);
    }

    private void initView() {
        mOne_stage_rv = (MyRecycleView) view.findViewById(R.id.one_stage_rv);
        mTwo_stage_rv = (MyRecycleView) view.findViewById(R.id.two_stage_rv);
        mThree_stage_rv = (MyRecycleView) view.findViewById(R.id.three_stage_rv);
        mline_two = view.findViewById(R.id.line_two);
        mline_one = view.findViewById(R.id.line_one);
    }

    private void initData() {
        allChannelsPresenter = new AllChannelsPresenter(mContext);
        allChannelsPresenter.setDisplayed(true);

        mOne_stage_rv.setFocusable(false);
        mTwo_stage_rv.setFocusable(false);
        mThree_stage_rv.setFocusable(false);
        //Toast.makeText(mContext, "开始加载数据", Toast.LENGTH_SHORT).show();

    }

    private void loadData() {
        Bundle bundle = new Bundle();
        bundle.putString("url", Paths.HOSTPATH + Paths.CHANNEL_PATH);
        allChannelsPresenter.loadItem(bundle, this);
    }


    private void selectIndex() {

        categoryIndex = 0;
        PlayerActivity activity = (PlayerActivity) getActivity();
        int indexId = activity.getIndexId();
        Log.d("PlayWindowFragment", "indexId:" + indexId);
        if (null != allChannelsPresenter.listContent) {
            for (MainChanel chanel : allChannelsPresenter.listContent) {

                if (null != chanel.getLives()) {
                    channelIndex = 0;
                    for (MainChanel.Lives lives : chanel.getLives()) {
                        if (indexId == lives.getId()) {
                            return;
                        }
                        channelIndex++;
                    }
                }
                categoryIndex++;
            }
        }

        Log.d("TAG", "loadData:" + activity.getIndex() + ":" + activity.getIndexId());

    }

    private void setLisenter() {
        allChannelsPresenter.onBindAllChannels(channelsViewHolder);
        mOne_stage_rv.setOnKeyListener(new FirstChannelOnKey());
        mTwo_stage_rv.setOnKeyListener(new SencondChannelOnKey());
        mThree_stage_rv.setOnKeyListener(new ThirdChannelOnKey());
        mOne_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mOne_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mOne_stage_rv.getChildCount() > 0) {
                                firstAdapter.selected();
                            }
                        }
                    });
                }
            }
        });
        mTwo_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mTwo_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mTwo_stage_rv.getChildCount() > 0) {
                                //获取当前的节目
                                if (categoryIndex == firstAdapter.getPosition()) {
                                    if (sencondAllAdapter.getPosition() != 0) {
                                        sencondAllAdapter.selected();
                                    } else {
                                        sencondAllAdapter.selected(channelIndex);
                                    }
                                } else {
                                    sencondAllAdapter.selected(0);
                                }
                            }
                        }
                    });
                }
            }
        });
        mThree_stage_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    mThree_stage_rv.post(new Runnable() {
                        @Override
                        public void run() {
                            //Toast.makeText(mContext, "获取到焦点", Toast.LENGTH_SHORT).show();
                            if (mThree_stage_rv.getChildCount() > 0) {
                                thirdAdapter.selected();
                            }
                        }
                    });
                }
            }
        });
    }


    @Override
    public void onError(int code, String msg) {

    }

    @Override
    public void onMovieCompleted(AllChannelsPresenter presenter, int count) {

        firstAdapter = new MainChanelAdapter(presenter);
        mOne_stage_rv.setLayoutManager(new FocusGridLayoutManager(mContext, 1));
        firstAdapter.setCount(count);
        mOne_stage_rv.setAdapter(firstAdapter);

        mOne_stage_rv.setFocusable(true);
        selectIndex();
        mHandler.sendEmptyMessageDelayed(FIRST_LIST, 300);
        APPLog.printInfo("设置直播数据适配器");

        firstAdapter.selected(categoryIndex);

        //Toast.makeText(mContext, "数据下载解析完成", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onChannelCompleted(AllChannelsPresenter presenter, int count) {

        APPLog.printDebug("onChannelCompleted " + count);


        sencondAllAdapter = new ChanelAllAdapter(presenter);
        FocusGridLayoutManager manager = new FocusGridLayoutManager(mContext, 1);
        mTwo_stage_rv.setLayoutManager(manager);
        sencondAllAdapter.setCount(count);
        sencondAllAdapter.setMainHandler(mainHandler);
        mTwo_stage_rv.setAdapter(sencondAllAdapter);

        mTwo_stage_rv.setFocusable(true);
    }

    @Override
    public void onProgramCompleted(AllChannelsPresenter presenter, int count) {
        thirdAdapter = null;
        thirdAdapter = new ProgramAdapter(presenter, mContext);
        mThree_stage_rv.setLayoutManager(new FocusGridLayoutManager(mContext, 1));
        thirdAdapter.setCount(count);
        thirdAdapter.setMainHandler(mainHandler);
        mThree_stage_rv.setAdapter(thirdAdapter);
        mThree_stage_rv.setFocusable(true);
    }

    private AllChannelsPresenter.AllChannelsViewHolder channelsViewHolder = new AllChannelsPresenter.AllChannelsViewHolder() {
        @Override
        public void setmThreeStageRv(boolean isShow) {
            if (isShow) {
                mThree_stage_rv.setVisibility(View.VISIBLE);
            } else {
                mThree_stage_rv.setVisibility(View.GONE);
            }
        }

        @Override
        public void setLineTwoView(boolean isShow) {
            if (isShow) {
                mline_two.setVisibility(View.VISIBLE);
            } else {
                mline_two.setVisibility(View.INVISIBLE);
            }
        }

        @Override
        public void setLineOneView(boolean isShow) {
            if (isShow) {
                mline_one.setVisibility(View.VISIBLE);
            } else {
                mline_one.setVisibility(View.INVISIBLE);
            }
        }
    };

    public class FirstChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if (mHandler.hasMessages(HIDE_FRAGMENT)) {
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT, 6000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = firstAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = firstAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                mTwo_stage_rv.requestFocus();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return true;
        }
    }

    public class SencondChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if (mHandler.hasMessages(HIDE_FRAGMENT)) {
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT, 6000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {

                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = sencondAllAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = sencondAllAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {

                mThree_stage_rv.requestFocus();
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) && event.getAction() == KeyEvent.ACTION_DOWN) {
                sencondAllAdapter.onClick();
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                mOne_stage_rv.requestFocus();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return false;
        }
    }

    public class ThirdChannelOnKey implements View.OnKeyListener {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            int action = event.getAction();
            if (mHandler.hasMessages(HIDE_FRAGMENT)) {
                mHandler.removeMessages(HIDE_FRAGMENT);
            }
            mHandler.sendEmptyMessageDelayed(HIDE_FRAGMENT, 6000);
            if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = thirdAdapter.selectedNext(); // 下面是否有item
                    //Toast.makeText(AllChannelsActivity.this, "下==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                if (action == KeyEvent.ACTION_DOWN) {
                    focusPosition = thirdAdapter.selectedPre();
                    //Toast.makeText(AllChannelsActivity.this, "上==》："+ focusPosition, Toast.LENGTH_SHORT).show();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && action == KeyEvent.ACTION_DOWN) {
                mTwo_stage_rv.requestFocus();
                thirdAdapter.unselected();
                return true;
            } else if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) && action == KeyEvent.ACTION_DOWN) {
                boolean flag = thirdAdapter.onClick();
                if (flag) {
                    fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                }
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                fragmentManager.beginTransaction().remove(PlayWindowFragment.this).commit();
                return true;
            }
            return false;
        }
    }
}
